



//
//  NHomeViewController.m
//  nncloud
//
//  Created by macfai on 2018/9/17.
//  Copyright © 2018年 youedata. All rights reserved.
#import "CheckViewController.h"
#import "CollectViewController.h"
#import "EquipTypeSwitchViewController.h"
#import "PrintViewController.h"
#import "AddNewEquipmentViewController.h"
#import "equipDetailModel.h"
#import "FilterViewController.h"
#import "RelayListModel.h"
#import "stationModel.h"
#import "UserCenterViewController.h"
#import "RelayDetailViewController.h"
#import "LineSelectViewController.h"
#import "LineNameView.h"
#import "ZFScanViewController.h"
#import "PPBadgeView.h"
#import "NMessageViewController.h"
#import "NFeedbackPopView.h"
#import "NHomeViewController.h"
#import "NHomeCell.h"
#import "NHomeSectionHeader.h"
#import "NHomeHeaderView.h"
#import "NProblemContentViewController.h"
#import "NMyFeedbackViewController.h"
#import <MJRefresh/MJRefresh.h>
#import <MJExtension/MJExtension.h>
#import "NFeedbackModel.h"
#import "NFeedbackCell.h"
#import "NWriteMsgViewController.h"
#import "NProcessInstrucitonViewController.h"
#import "MMenu.h"
#import "SearchBar.h"
#import "RelayCell.h"

@interface NHomeViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NHomeHeaderView *headerView;

@property (nonatomic,strong)NSMutableArray *dataArray;

///
//@property (nonatomic,strong)NSMutableArray *detailDataArray;

@property (nonatomic,assign)NSInteger currentPage;

@property (nonatomic,strong)SearchBar *searchBar;

@property (nonatomic,strong)LineNameView *lineName;

@property (nonatomic,strong)NSMutableArray *dictArray;

///将线和站的信息传递到下个页面的字典
@property (nonatomic,strong)NSMutableDictionary *transDict;

///
@property (nonatomic,assign)BOOL isScan;

@property (nonatomic,copy)NSString *scanResult;

///当前设备总数
@property (nonatomic,strong)NSNumber *totalCount;

@property (nonatomic,strong)UILabel *countLabel;

///列表名称
@property (nonatomic,strong)UILabel *ttLabel;


@end

#define cellIdentifier  @"relay"
#define HeaderHight  290
#define PageSize 20


@implementation NHomeViewController

-(UITableView *)tableView{
    if (!_tableView) {
        WeakStament(ws);
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 64, ScreenWidth , ScreenHeight - TabBarHeight-NavBarHeight-45) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 132.0f;
//        _tableView.separatorColor = [UIColor clearColor];
        _tableView.backgroundColor = kBackgroundColor;
        [_tableView registerNib:[UINib nibWithNibName:@"RelayCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [ws refresh];
        }];
        ////如果是扫码进来的话没有分页
        if ([NUserModel shareInstance].comeinWithScan==NO) {
            _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                [ws loadMoreData];
            }];
        }
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];
        
    }
    return _tableView;
}

#pragma mark - 点击进入线别选择
- (void)tapLineAction:(UITapGestureRecognizer *)tap{
    LineSelectViewController *ses = [[LineSelectViewController alloc]init];
    [self.navigationController pushViewController:ses animated:YES];
}


- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    ///全局标记
    [NUserModel shareInstance].equipType = @"r";
    
    self.searchBar.hidden = false;
    self.ttLabel.hidden = false;
    self.lineName.lineLab.text = [NUserModel shareInstance].currentLine?:@"";
    self.lineName.stationLab.text = [NUserModel shareInstance].currentStation?:@"";
    ///这个是标记线站选择后 进入首页设备列表后  刷新
    if ( [NUserModel shareInstance].currentSelect == YES) {
         [self refresh];
        [NUserModel shareInstance].currentSelect = false;
    }
    
    if ([NUserModel shareInstance].commitUpdate==YES) {
        [self refresh];
        [NUserModel shareInstance].commitUpdate = false;
    }
    

    ///从筛选页面过来的数据  数据筛选
//    if ([NUserModel shareInstance].isFilter==YES) {
//        [self filterData];
//        [NUserModel shareInstance].isFilter = false;
//    }
    
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.searchBar.hidden = YES;
    self.ttLabel.hidden = YES;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.dataArray = [NSMutableArray array];
    self.dictArray = [NSMutableArray array];
//    NSArray *arr = @[@"",@"",@"",@"",@"",];
//    YYLog(@"空字符串也可以：%lu",(unsigned long)arr.count);
    self.currentPage = 1;
//    self.view.backgroundColor = kWhiteColor;
//    self.navigationItem.leftBarButtonItem = nil;
    [self.navigationItem setItemWithTitle:@"继电器" textColor:kNavigationTitleColor fontSize:18 itemType:center];
//    [self addNavigationLeftButtonFrame:CGRectMake(0, 0, 30, 30) Image:nil AndHighLightImage:nil AndText:@"返回" Target:self Action:@selector(headAction:)];
    [self addNavgationRightButtonWithFrame:CGRectMake(0, 0, 30, 30) title:@"" Image:@"nav_scan" selectedIMG:nil tartget:self action:@selector(scan)];
    [self.view addSubview:self.tableView];
    [self addSearchBar];
    //线别
    [self addLineNameView];
    
    if ([NUserModel shareInstance].comeinWithScan==YES) {
        [self loadScanData];
    }else{
        [self loadData];
    }
}

#pragma mark - 添加搜索框
- (void)addSearchBar{
    SearchBar *bar = [[[NSBundle mainBundle]loadNibNamed:@"SearchBar" owner:self options:nil]lastObject];
    bar.frame = CGRectMake(100, 7, ScreenWidth-150, 30);
    bar.layer.cornerRadius = 15.f;
    bar.layer.masksToBounds = YES;
    bar.textFd.delegate = self;
    bar.textFd.returnKeyType = UIReturnKeySearch;
    self.searchBar = bar;
    [self.navigationController.navigationBar addSubview:bar];
    
    UILabel *ttLabel = [[UILabel alloc]initWithFrame:CGRectMake(35, 3, 60, 36)];
    ttLabel.text = @"继电器设备列表";
    ttLabel.font = kFont14;
    ttLabel.numberOfLines = 2;
    ttLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    ttLabel.textColor = kWhiteColor;
    ttLabel.backgroundColor = kClearColor;
    [self.navigationController.navigationBar addSubview:ttLabel];
    self.ttLabel = ttLabel;
}

#pragma mark - 键盘  搜索  代理
//搜索虚拟键盘响应
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"点击了搜索");
    [self.searchBar.textFd resignFirstResponder];
    //进行搜索
    [self refresh];
    return YES;
}
#pragma mark - 清除搜索框
///
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    
    YYLog(@"点击了清空按钮");
    [self.searchBar.textFd resignFirstResponder];
    [self.view endEditing:YES];
    self.searchBar.textFd.text = @"";
    [self refresh];
    
    [self.tableView scrollsToTop];
    
    return YES;
    
}
#pragma mark - 线名view
-(void)addLineNameView{
    self.lineName = [[[NSBundle mainBundle]loadNibNamed:@"LineNameView" owner:self options:nil]lastObject];
    self.lineName.frame = CGRectMake(0, 0, ScreenWidth, 62);
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapLineAction:)];
    [self.lineName addGestureRecognizer:tap];
    [self.view addSubview:self.lineName];
    [self.view bringSubviewToFront:self.lineName];
    [self addBottomBuyView];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-60, 16, 50, 30)];
    label.backgroundColor = kMagentaColor;
    self.countLabel = label;
//    [self.lineName addSubview:label];
}

//
- (void)backItemClick{
    [self headAction:nil];
}

#pragma mark - 点击头像
- (void)headAction:(UIButton *)btn{
    
    [self.tabBarController.navigationController popViewControllerAnimated:NO];
//    [self.navigationController popViewControllerAnimated:YES];
//    UserCenterViewController *center = [UserCenterViewController new];
//    [self.navigationController pushViewController:center animated:YES];
}

- (void)scan {
    
//    /扫码
    ZFScanViewController * vc = [[ZFScanViewController alloc] init];
    vc.returnScanBarCodeValue = ^(NSString * barCodeString){
        [AFToast showText:barCodeString];
//        self.resultLabel.text = [NSString stringWithFormat:@"扫描结果:\n%@",barCodeString];
        YYLog(@"扫描结果的字符串======%@",barCodeString);
        
        if (barCodeString.length>5) {
            self.scanResult = barCodeString;
            self.isScan = YES;
            [self loadData];
        }else{
            [AFToast showText:@"当前扫描结果无效"];
        }
    };
    
    [self presentViewController:vc animated:YES completion:nil];
    
}
#pragma mark - 工作流页面进来
///通过最外层的扫描进来的
-(void)loadScanData{
    
    ///这个接口调用了两次，在外面时是调用拿到器材类型，进来时候调用是拿到具体的器材信息
    [self.dataArray removeAllObjects];
    NSDictionary *dict = @{@"brokenNumber":[NUserModel shareInstance].scanBrokenNumber?:@""};
    [NNetworkClient postRequestWithBaseUrl:kScanUrl setParameters:dict success:^(id responseObject) {
        YYLog(@"%@",responseObject);
        if ([responseObject[@"status"]integerValue]==0) {
            
            NSArray *arr = responseObject[@"data"];
            for (NSDictionary *dict in arr) {
                equipDetailModel *model = [equipDetailModel mj_objectWithKeyValues:[dict deleteNull]];
                [self.dataArray addObject:model];
            }
            
            ///扫描用完一次本次bool 生命循环结束
            [NUserModel shareInstance].comeinWithScan = false;
            
            self.dictArray = [arr copy];
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
            [self endRefresh];
            ///这个放的位置很重要  加载更多没有数据处理
            if (arr.count==0) {
                [self noMoreData];
            }
            
        }else{
            
            [AFToast showText:responseObject[@"message"]];
            
        }
    } fail:^(NSError *error) {
        
    } delegater:nil];
    
}
#pragma mark - 获取数据 正常的列表数据
- (void)loadData{
    
    WeakStament(ws);
//    NSString *sss = [NUserModel shareInstance].currentStation;
//    if (!sss) {
//        return;
//    }
    if (self.currentPage==1) {
        
        [self.dataArray removeAllObjects];
    }
    
    ///type 1继电器  2转辙机  3综合器材  brokenNumber 段编号这个参数主要是在搜索时候用
    NSDictionary *dict;
    if (self.isScan==YES) {
        dict = @{@"type":@"1",@"brokenNumber":self.scanResult?:@"",@"stationName":[NUserModel shareInstance].currentStation?:@"",@"currentPage":@(self.currentPage)};
        self.isScan = false;
        
    }else{
      dict = @{@"type":@"1",@"brokenNumber":self.searchBar.textFd.text?:@"",@"stationName":[NUserModel shareInstance].currentStation?:@"",@"currentPage":@(self.currentPage)};
    }
    
    
    [SVProgressHUD show];
    
    [NNetworkClient postRequestWithBaseUrl:kInqueryStationUrl setParameters:dict success:^(id responseObject) {
        YYLog(@"%@",responseObject);
        if ([responseObject[@"status"]integerValue]==0) {
            
            NSArray *arr = responseObject[@"data"][@"lists"];
            self.totalCount = responseObject[@"data"][@"totalCount"];
            YYLog(@"uuuu%@",self.totalCount);
            self.countLabel.text = [NSString stringWithFormat:@"%@",self.totalCount];
            for (NSDictionary *dict in arr) {
//                RelayListModel *model = [RelayListModel mj_objectWithKeyValues:dict];
                
                equipDetailModel *model = [equipDetailModel mj_objectWithKeyValues:[dict deleteNull]];
                [self.dataArray addObject:model];
            }
            
//            self.dictArray = (NSMutableArray *)arr;
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
            [ws endRefresh];
            
            ///这个放的位置很重要  加载更多没有数据处理
            
            if (arr.count==0) {
                [ws noMoreData];
            }
        }
    } fail:^(NSError *error) {
        YYLog(@"%@",error);
        [SVProgressHUD dismiss];
    } delegater:nil];
}
- (void)refresh {
    self.currentPage = 1;
    [self loadData];
}
- (void)loadMoreData{
    
    self.currentPage++;
    
    if ([NUserModel shareInstance].isFilter==YES) {
        
        
        
    }else{
        
         [self loadData];
    }
   
    
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

- (void)noMoreData {
    [self.tableView reloadData];
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}


#pragma mark - datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
//    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    RelayCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
//    RelayListModel *model = self.dataArray[indexPath.row];
    equipDetailModel *model;
    if (self.dataArray.count>indexPath.row) {
    
        model = self.dataArray[indexPath.row];
        
    }
    
    if (self.dataArray.count>indexPath.row) {
        cell.bianhaoLab.text = model.duanbianhao;
        cell.xinghaoLab.text = model.xinghao;
        cell.stationLab.text = model.zhanming;
        cell.positionLab.text = model.zuheweizhi;
        cell.typeNameLabel.text = model.qicaizhonglei;
    }
    return cell;
}


#pragma mark - delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSDictionary *dict = self.dictArray[indexPath.row];
//    RelayListModel *model = self.dataArray[indexPath.row];
//    NFeedbackModel *model = self.dataArray[indexPath.row];
    equipDetailModel *model = self.dataArray[indexPath.row];
    RelayDetailViewController *proc = [RelayDetailViewController new];
//    EquipTypeSwitchViewController *proc = [EquipTypeSwitchViewController new];
    ///给打印做标记
    [NUserModel shareInstance].printType = @"r";
    proc.flag = @"r";
    proc.model = model;
    [self.navigationController pushViewController:proc animated:YES];
}

#define BarHeight 45.f
///添加底部view
- (void)addBottomBuyView{
    
    UIButton *cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cartBtn.frame = CGRectMake(0, ScreenHeight-BarHeight-TabBarHeight-NavBarHeight, ScreenWidth/2-1, BarHeight);
    cartBtn.backgroundColor = kSystemtBlue;
    [cartBtn addTarget:self action:@selector(cartAction:) forControlEvents:UIControlEventTouchUpInside];
    [cartBtn setTitle:@"筛选" forState:UIControlStateNormal];
    [self.view addSubview:cartBtn];
    
    UIButton *gouBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    gouBtn.frame = CGRectMake(ScreenWidth/2, ScreenHeight-BarHeight-TabBarHeight-NavBarHeight, ScreenWidth/2, BarHeight);
    gouBtn.backgroundColor = kSystemtBlue;
    [gouBtn addTarget:self action:@selector(gouAction:) forControlEvents:UIControlEventTouchUpInside];
    [gouBtn setTitle:@"新增设备" forState:UIControlStateNormal];
    [self.view addSubview:gouBtn];
}

#pragma mark - 筛选
///筛选  设备核对
- (void)cartAction:(UIButton *)btn
{
//    WeakStament(ws);
//    ZFScanViewController * vc = [[ZFScanViewController alloc] init];
//    vc.returnScanBarCodeValue = ^(NSString * barCodeString){
//        YYLog(@"%@",barCodeString);
////        [ws goCheck];
//    };
////    [self presentViewController:vc animated:YES completion:nil];
//    [self presentViewController:vc animated:YES completion:^{
//    }];
   
///之前做的筛选功能  后这里换成采集功能
    equipDetailModel *model = [self.dataArray firstObject];
    FilterViewController *filter = [FilterViewController new];
    filter.flag = @"r";
    filter.model = model;
    [self.navigationController pushViewController:filter animated:YES];
}

#pragma mark - 新增设备//2019.7月功能修改为设备采集
- (void)gouAction:(UIButton *)btn
{
    
    ///
//    CollectViewController *collect = [CollectViewController new];
//    [self.navigationController pushViewController:collect animated:YES];
    equipDetailModel *model = [self.dataArray firstObject];
    AddNewEquipmentViewController *add = [AddNewEquipmentViewController new];
    add.flag = @"r";
    add.model = model;
    [self.navigationController pushViewController:add animated:YES];
}

-(void)goCheck{
    CheckViewController *check = [CheckViewController new];
    [self.tabBarController.navigationController pushViewController:check animated:YES];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

@end
